<template>
  <div>
   <div>
     <span style="margin-right: 20px">字典一级:</span>
     <el-select v-model="dictLevel1Code">
       <el-option
         v-for="item in dictLevel1"
         :key="item.id"
         :label="item.name"
         :value="item.code">
       </el-option>
     </el-select>
     <span style="margin-right: 20px">名字:</span>
     <el-input v-model="dictLevel2Name" style="width: 150px;margin-right: 20px"></el-input>
     <el-button type="primary" @click="addDictLevel2">添加二级</el-button>
   </div>
    <el-table
      :data="tableData"
      :span-method="spanMethod"
      border
      highlight-current-row
      style="width: 100%; margin-top: 20px">
      <el-table-column
        prop="parentName"
        label="一级">
      </el-table-column>
      <el-table-column
        prop="name"
        label="二级">
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="danger" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import {deleteDict, getDict, getDictLevel1, addDict} from '@/api/module/dict'
import {groupBy, get} from 'lodash'
export default {
  name: 'index',
  data () {
    return {
      tableData: [],
      tableInfo: {},
      dictLevel1: [],
      dictLevel1Code: '',
      dictLevel2Name: ''
    }
  },
  mounted () {
    this.getDict()
    this.getDictLevel1()
  },
  methods: {
    spanMethod ({rowIndex, columnIndex}) {
      if (columnIndex === 0) {
        if (get(this.tableInfo, rowIndex)) {
          return [get(this.tableInfo, rowIndex), 1]
        } else {
          return [0, 0]
        }
      }
    },
    initTableData () {
      let startIndex = 0
      Object.values(groupBy(this.tableData, 'parentCode')).forEach(arrays => {
        this.$set(this.tableInfo, startIndex, arrays.length)
        startIndex += arrays.length
      })
    },
    getDict () {
      getDict().then(data => {
        if (get(data, 'data.data')) {
          this.tableData = get(data, 'data.data')
        }
      }).then(() => {
        this.initTableData()
      })
    },
    getDictLevel1 () {
      getDictLevel1().then(res => {
        this.dictLevel1 = get(res, 'data.data', [])
      })
    },
    handleDelete (row) {
      deleteDict(row.code).then(() => {
        this.$router.go(0)
      })
    },
    addDictLevel2 () {
      addDict(this.dictLevel1Code, this.dictLevel2Name).then(() => {
        this.$router.go(0)
      })
    }
  }
}
</script>
